<?php
class AcosController extends AppController {
	public $name = 'Acos';
	public $uses=array('Acos','Group');
	public $helpers=array('Common');
	
	function admin_index(){
		//get filter field
		//filterField dùng cho combobox search của trang liet ke danh sach, khai bao cac field co the search cua danh sach. 
		$filterField=array(				
			$this->uses[0].'.name'=>_resource('name',true),	
		);
		$this->set('filterField',$filterField);
		
	}	
	
function admin_lists(){
		//khoi tao cac session can thiet cho 1 model, session nay dung de luu lai trang thai cua 1 model nhu phan trang, sort tang giam, dieu kien search, id cha...
		//cac su dung Session cua cakephp : doc them trong book.cakephp.org
		if(!$this->Session->check($this->uses[0])){
			//khoi tao array vao bien $tmp
			$tmp=array(
				'limit'=>90,
				'conditions'=>'',
				'fields'=>null,
				'order'=>'lft',
				'page'=>1,
				'recursive'=>0,
				'sortField'=>null,
				'sortDir'=>'asc',				
				'filterField'=>'',
				'filterText'=>'',
				'catid'=>'',
			);
			//luu vao session
			$this->Session->write($this->uses[0],$tmp);			
		}
		
		
		
		//su dung khi site co chuc nang da ngon ngu==========================
		//khai bao ngon ngu cua model, khi lay data, thi model nay se lay cac data theo ngon ngu da duoc chon
		$this->{$this->uses[0]}->locale=$this->Session->read('adminLang');
		//===================================================================
		
		//doc ra cac trang thai cua 1 model da luu trong session
		// truyen vao bien paginate, khi lay data, model se dua vao cac gia tri cua bien nay de search, sort, phan trang ... 
		$this->paginate=$this->Session->read($this->uses[0]);				
		//ham paginate() la ham ho tro phan trang, khi dung ham nay, se tu dong phan trang theo cac gia tri trong bien paginate o tren
		//lay data da duoc phan trang va truyen vao bien $data0
		$data0=$this->paginate($this->uses[0]);
		unset($data0[0]);
		//edit for retrieve tree
		$tree=$this->{$this->uses[0]}->generateTreeList(null,"{n}.".$this->uses[0].".id","{n}.".$this->uses[0].".name",'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
		
		foreach($data0 as $k=>$v){
			$data0[$k][$this->uses[0]]['name']=$tree[$data0[$k][$this->uses[0]]['id']];
		}
		//set bien $data0 ra view de hien ra luoi.
		$this->set('data0',$data0);
		//render view va cho cakephp biet day la view cua ajax -> khi do, cakephp se chi render view ma khong render toan bo layout cua website. 
		$this->render('admin_lists','ajax');
	}
	
	function admin_add($isBuild=0,$isRebuild=0){
		//group
		$log=null;
		$group =& $this->Group;
		$firstGroup=$this->Group->find('first');
		$group->id=$firstGroup['Group']['id'];
		if($isRebuild && $isBuild){
			$this->Acos->query('truncate table '.$this->Config->tablePrefix.'aros_acos');
			$this->Acos->query('truncate table '.$this->Config->tablePrefix.'acos');
		}
		//create root
		
		$aco =& $this->Acl->Aco;
        $root = $aco->node('controllers');
        
        if (!$root) {
            $aco->create(array('parent_id' => null, 'model' => null, 'alias' => 'controllers'));
            $root = $aco->save();
            
            $root['Aco']['id'] = $aco->id; 
            $log['Root'][] = 'Created ROOT node for controllers';
        } 
        else {
            $root = $root[0];
        }
		// Get Controllers and Controller's Methods
 		$path = CONTROLLERS;
 		App::uses('Folder','Utility');
 		$folder =& new Folder($path);
 		$controllers = $folder->read(); 		
 		$methods = array(); 		
 		foreach($controllers[1] as $controller){
 			$className = str_replace('Controller.php','',$controller); 			
 			if(!in_array($className,$this->Common->baseController())){
	 			
	 			// find / make controller node
	 			$controllerNode=null;
	 			if(!$isRebuild)$controllerNode = $aco->node('controllers/'.$className);
	 			//t($controllerNode,0);
	            if (!$controllerNode) {
	            	if($isBuild){
		                $aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => $className, 'name' => $className));	                
		                $controllerNode = $aco->save();
		                $controllerNode['Aco']['id'] = $aco->id;
		                $log['Module'][] = 'Created Aco node for '.$className;
		                $this->Acl->allow($group,$className);
	            	}
	            	else{
	            		$log['Module'][]=$className;	            		
	            	}
	            } else {
	                $controllerNode = $controllerNode[0];
	            }
	 			//$methods[$className][$className] = $className;
	 			//t($className,0);
	 			
	 			$classNames = $className."Controller";
	 			App::uses($classNames,'Controller');	 			
	 			$class =& new $classNames();	
	 			$_methods = get_class_methods($class); 
	 			foreach($_methods as $method){		
 					if(!strpos($method,"_nocheck_") && strpos($method,"_",0) !== 0 && !in_array($method,$this->Common->baseMethod()) && !in_array($className.'/'.$method,$this->Common->baseMethodController())){
 						$methods[$className][$method] = $method;
 						//get same permission
 						$methodPath=$this->Common->samePermission('controllers/'.$className.'/'.$method);
 						if($methodPath=='controllers/'.$className.'/'.$method){
	 						//t($methodPath,0);
	 						$methodNode=null;
	 						if(!$isRebuild)$methodNode = $aco->node($methodPath);
			                if (!$methodNode) {
			                	if($isBuild){
			                   	 	$aco->create(array('parent_id' => $controllerNode['Aco']['id'], 'model' => null, 'alias' => $method, 'name' => $method));
			                    	$methodNode = $aco->save();
			                    	if(strpos($method,"admin",0) === 0)
			                   	 		$log['Admin'][] = 'Created Aco node for '.$methodPath;
			                   	 	else $log['Website'][] = 'Created Aco node for '.$methodPath;
			                	}
			                	else{
			                		if(strpos($method,"admin",0) === 0)
			                   	 		$log['Admin'][] = $methodPath;
			                   	 	else $log['Website'][] = $methodPath;	  
			                	}
			                    //set permission for superadmin
			                    
			                  
			                }	
 						}
 					}	 					
	 				
	 			}	 	 			
 			} 			
 		}
 		if($isBuild && $isRebuild){ 			
 			$this->Session->write('message',_resource('these module are rebuild.',true));
 		}else if($isBuild){
 			$this->Session->write('message',_resource('these module are created.',true));
 		}
 		$this->set('data',$log);
 		$this->set('isRebuild',$isRebuild);
 		$this->set('isBuild',$isBuild);
 		if($isBuild)$this->set('isInsert',1);
 				
	}
	
	function admin_resetName($id=null){
		$this->Session->delete('error');
		//if is submit:		
	//if is submit:		
		if($this->request->is('post')){
			$id_arr=$this->data['check'];
		} else {
			$id_arr=null;
		}
		//if url
		if(intval($id)){
			$id_arr[$id]='';
		}
		if(count($id_arr)>0){
			//Xoa nhieu record
			$this->{$this->uses[0]}->query('update acos set name=alias where id in ('.implode(',',array_keys($id_arr)).')');
			
			if(!$this->Session->check('error')){
				$this->Session->write('message',_resource('update data successful',true));
			}
		} else {
			$this->Session->write('error',_resource('no information to delete',true));
		}
		$this->admin_lists();	
	}

	function admin_edit($id=null){
		$this->{$this->uses[0]}->recursive=0;
		
		$isInsert=false;
		if(!empty($this->data)){
			//t($this->data);
			if($this->{$this->uses[0]}->create($this->data) && $this->{$this->uses[0]}->validates()){
									
						$this->data[$this->uses[0]]['key']=htmlspecialchars($this->data[$this->uses[0]]['key']);						
						if($this->{$this->uses[0]}->save($this->data)) {							
							$this->data=null;
							$isInsert=true;							
							$this->Session->write('message',_resource('update data successful',true));						
						} else {
							$this->Session->write('error',_resource('can not update data',true));
						}
					
			}else{
				$this->Session->write('error',_resource('red fill is require',true));
			}
		}else{
			if($id!=null){
				$this->data=$this->{$this->uses[0]}->findById($id);	
				$this->set('listGroup',$this->{$this->uses[1]}->find('list',null,null,$this->uses[1].'.view_order'));	
				if(empty($this->data)){		
					$this->Session->write('error',_resource('data not found',true));			
					$this->render('admin_edit_not_found');
				}
			}
			else{				
				$this->Session->write('error',_resource('data not found',true));		
				$this->render('editNotFound');
			}
		}		
		
		$this->set('isInsert',$isInsert);
		
	}

	function admin_delete($id = null) {		
		$this->Session->delete('error');
		//if is submit:		
		if($this->request->is('post')){
			$id_arr=$this->data['check'];
		} else {
			$id_arr=null;
		}
		//if url
		if(intval($id)){
			$id_arr[$id]='';
		}
		if(count($id_arr)>0){
			//Xoa nhieu record
			$this->{$this->uses[0]}->query('delete from '.$this->{$this->uses[0]}->tablePrefix.$this->{$this->uses[0]}->table.' where id in ('.implode(',',array_keys($id_arr)).')' );			
		} else {
			$this->Session->write('error',_resource('no information to delete',true));
		}
		$this->admin_lists();		
	}
	
	
	
	function admin_sort($sortField=null,$sortDir='asc'){
		if($sortField){
			if($sortDir!='desc') $sortDir='asc';
			$this->Session->write($this->uses[0].'.sortField',$sortField);
			$this->Session->write($this->uses[0].'.sortDir',$sortDir);
			$this->Session->write($this->uses[0].'.order',$sortField.' '.$sortDir);
		}
		$this->admin_lists();
	}
	
	function admin_page($page=1){
		$this->Session->write($this->uses[0].'.page',$page);
		$this->admin_lists();
	}
	
	function admin_display($limit=0){
		if(intval($limit)){
			$this->Session->write($this->uses[0].'.limit',$limit);
		}
		$this->admin_lists();
	}

	function admin_filter(){
		if($this->request->is('post')){
			$this->Session->write($this->uses[0].'.filterText',$this->request->data['filter_text']);
			$this->Session->write($this->uses[0].'.filterField',$this->request->data['filter_field']);
			$conditions=$this->Session->read($this->uses[0].'.conditions');
			if(!empty($this->request->data['filter_text'])){				
				$conditions[$this->request->data['filter_field'].' like']='%'.$this->request->data['filter_text'].'%';				
			}
			else{
				unset($conditions[$this->request->data['filter_field'].' like']);
			}
			$this->Session->write($this->uses[0].'.conditions',$conditions);
		}
		$this->admin_lists();
	}
	
	

	//===========================================================

	

}
?>
